<template>
  <div style="width: 100%; height: 100%">
    <a-input-search
      v-model:value="searchValue"
      style="width: 100%; margin-bottom: 8px; padding: 0 15px"
      placeholder="搜索"
      @search="searchTree"
    />
    <div style="width: 100%; height: calc(100% - 42px); overflow: auto">
      <div>
        <a-tree
          v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          :field-names="{ title: 'name' }"
          :tree-data="treeData"
          checkable
        />
      </div>
    </div>
  </div>
</template>
<script>
import { defineComponent, ref, inject, watch } from 'vue'
import factory from '../../factory'
export default defineComponent({
  emits: ['treeNode-selected'],
  setup(props, ctx) {
    const { currentItemId } = inject('roleParams')
    const expandedKeys = ref([])
    const selectedKeys = ref([])
    const treeData = ref([{ key: '-1', name: '托管角色', children: [] }])
    const getFirstTree = (search = '') => {
      factory.searchTree(search, currentItemId.value.key).then((res) => {
        treeData.value[0].children = res.data
        expandedKeys.value = ['-1']
        selectedKeys.value = ['-1']
      })
    }
    getFirstTree()

    //==勾选树 =================
    const checkedKeys = ref([])
    let checkItems = []
    watch(checkedKeys, () => {
      checkItems = []
      getChecked(treeData.value)
      ctx.emit('treeNode-selected', checkItems)
    })
    const getChecked = (item) => {
      item.forEach((m) => {
        if (checkedKeys.value.includes(m.key) && m.isLeaf) {
          //只传叶子节点, 父节点不传
          checkItems.push({ key: m.key, name: m.name })
        }
        if (m.children) {
          getChecked(m.children)
        }
      })
    }

    //==搜索树=====
    const searchValue = ref('')
    const searchTree = () => {
      getFirstTree(searchValue.value)
    }

    //==清空选中的nodes=============
    const clearKey = () => {
      checkedKeys.value = []
    }

    return {
      expandedKeys,
      selectedKeys,
      checkedKeys,
      treeData,
      searchValue,
      searchTree,
      clearKey,
    }
  },
})
</script>
